﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using Common.DBOper;
using System.Threading;
using TCPIPControl.StructHelper;
using TCPIPControl;
using TcpLabCommon;
using VibrationTest.OnLineChart;
using System.Windows.Forms.DataVisualization.Charting;

namespace VibrationTest
{
    public partial class frmRun : Form
    {
        public frmRun()
        {
            InitializeComponent();
            Program.formRun = this;
        }
        OperateTest opertest = new OperateTest();
        public Thread headbeatThread = null;
        TcpIpControl tp = null;
        Cls_SocketSet socketset = new Cls_SocketSet();
        OperateChannel opertechannel = new OperateChannel();
        int[] axis_txt = new int[31] { 10, 13, 16, 20, 25, 32, 40, 50, 63, 79, 100, 126, 158, 200, 251, 316, 398, 501, 631, 794, 1000, 1259, 1585, 1995, 2512, 3162, 3981, 5012, 6310, 7943, 10000 };
        private void bt_run_Click(object sender, EventArgs e)
        {
            if (Mdl_Class.TestModel == 1)
            {
                MessageBox.Show("系统正在进行信号检测,不能进行实验测试！", "提示");
                return;
            }
            if (ReturnIsOk()==false)
            {
                return;
            }
            if (Convert.ToInt32(this.txt_AverageNo.Text)>255) 
            {
                MessageBox.Show("平均次数不能大于255","提示");
            }
            Mdl_Class.onlinchannelData.Clear();
            //Acceleration_256 acc256 = new Acceleration_256();
            //byte[] b = Activator.CreateInstance<StructHelper>().Serialize(acc256);
            Mdl_Class.TestProgress = 0;
            Mdl_Class.TestId = Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmss"));
            Mdl_Class.TestName = this.txt_testName.Text.Trim();
            Mdl_Class.SampFreq = Convert.ToInt32(this.cmb_bandwidth.Text);
            Mdl_Class.SampFreq_index = Convert.ToInt32(this.cmb_bandwidth.SelectedIndex+1);
            Mdl_Class.LineNO = Convert.ToInt32(this.cmb_specLines.Text);
            MdlClass_TCP.LineNum= Convert.ToInt32(this.cmb_specLines.Text);
            Mdl_Class.AverageNO = Convert.ToInt32(this.txt_AverageNo.Text);
            Mdl_Class.AverageMod = Convert.ToInt32(this.cmb_AverageMod.SelectedIndex+1);
            Mdl_Class.WindowFunction = Convert.ToInt32(this.cmb_window.SelectedIndex+1);
            Mdl_Class.AverageMod_Name = this.cmb_AverageMod.Text;
            Mdl_Class.WindowFunction_Name = this.cmb_window.Text;
            //this.bt_run.BackColor = Color.Lime;
            //this.bt_stop.BackColor = Color.White;
            //SaveData savedata = new SaveData();

            //Acceleration_256 a_256 = new Acceleration_256();
            //a_256.Year = 2021;
            //a_256.Month = 11;
            //a_256.Day = 17;
            //a_256.Hour=13;
            //a_256.Minute=14;
            //a_256.Second=55;
            //a_256.MSecond=112;
            // a_256._1_3octavedB=new float[31];
            //a_256._1_3octavedB[0] = 1;
            //a_256._1_3octavedB[1] = 2;
            //a_256._1_3octavedB[30] = 99;

            //a_256.accelerationFFTAmpDB=new float[256];
            //a_256.accelerationFFTAmpDB[0] = 22;
            //a_256.accelerationFFTAmpDB[1] = 33;
            //a_256.accelerationFFTAmpDB[255] = 44;

            //a_256.accelerationTimewave=new float[512];
            //a_256.accelerationTimewave[0] = 55;
            //a_256.accelerationTimewave[1] = 66;
            //a_256.accelerationTimewave[511] = 77;

           
            //a_256.ChannelId = 1;
            //a_256.highdB = 20;
            //a_256.lowdB = 30;
            //a_256.totaldB = 40;
            //a_256.velocityRMS = 50;
            //Mdl_Class.LineNO = 256;
            //Mdl_Class.accdatalist.Add(a_256);
            //savedata.SaveAccData();
            //Mdl_Class.accdatalist.Clear();

            //Acceleration_512 a_512= new Acceleration_512();
            //a_512.Year = 2021;
            //a_512.Month = 11;
            //a_512.Day = 18;
            //a_512.Hour = 13;
            //a_512.Minute = 14;
            //a_512.Second = 55;
            //a_512.MSecond = 112;
            // a_512._1_3octavedB=new float[31];
            //a_512._1_3octavedB[0] = 4;
            //a_512._1_3octavedB[1] = 5;
            //a_512._1_3octavedB[30] = 88;

            // a_512.accelerationFFTAmpDB=new float[512];
            //a_512.accelerationFFTAmpDB[0] = 122;
            //a_512.accelerationFFTAmpDB[1] = 133;
            //a_512.accelerationFFTAmpDB[255] = 144;

            //a_512.accelerationTimewave=new float[1024];
            //a_512.accelerationTimewave[0] = 155;
            //a_512.accelerationTimewave[1] = 166;
            //a_512.accelerationTimewave[511] =177;


            //a_512.ChannelId = 2;
            //a_512.highdB = 120;
            //a_512.lowdB = 130;
            //a_512.totaldB = 140;
            //a_512.velocityRMS = 150;
            //Mdl_Class.LineNO = 512;
            //Mdl_Class.accdatalist.Add((object)a_512);
            //savedata.SaveAccData();

            //Mdl_Class.accdatalist.Clear();txt_AverageNo
            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = Convert.ToInt32(this.txt_AverageNo.Text)+1;
            Mdl_Class.TestModel =2;
            if (InitUnit())
            {
                this.timer1.Start();
                timer2.Start();
            }
            else 
            {
                Mdl_Class.TestModel = 0;
                MessageBox.Show("连接下位机失败！", "提示");
            }
        }

        private void bt_stop_Click(object sender, EventArgs e)
        {
            if (Mdl_Class.LowerMachineIsConnect&&this.progressBar1.Value < this.progressBar1.Maximum)
            {
                if (MessageBox.Show("测试还未结束，数据将丢失，确定要结束吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.Yes)
                {
                    this.timer1.Stop();
                    timer2.Stop();
                    Mdl_Class.SendInstruct = "stopdata";
                    if (tp != null)
                    {
                        tp.SendString(Mdl_Class.SendInstruct);
                    }
                
                    Mdl_Class.IsQuitProgram = true;
                    Thread.Sleep(1000);
                    if (tp != null)
                    {
                        tp.SendString(Mdl_Class.SendInstruct);
                        tp.Dispose();
                        tp = null;
                    }
                    this.bt_run.BackColor = Color.White;
                    this.bt_stop.BackColor = Color.Lime;
                    this.bt_run.Enabled = true;
                    this.bt_stop.Enabled = false;
                    this.lb_connectstate.Text = "下位机状态:已断开";
                    this.lb_connectstate.ForeColor = Color.Red;
                    Mdl_Class.LowerMachineIsConnect = false;
                    progressBar1.Value = 0;
                    Mdl_Class.TestModel = 0;
                }
            }
          
        }


        private void frmRun_Load(object sender, EventArgs e)
        {
            this.cmb_bandwidth.SelectedIndex = 1;
            this.cmb_specLines.SelectedIndex = 8;
            this.cmb_AverageMod.SelectedIndex = 0;
            this.cmb_window.SelectedIndex = 0;
            LoadChannel();
            this.cmb_dataType.SelectedIndex = 0;

            this.txt_time.Text = Convert.ToInt32(Convert.ToDouble(txt_AverageNo.Text) / Convert.ToDouble(txt_resolution.Text)).ToString();
        }



        public bool ReturnIsOk()
        {
           

            if(Mdl_Class.NowStectionId==0)
            {
                 MessageBox.Show("请选择section", "提示");
                  return false;
            }
            if (this.txt_testName.Text.Trim() == "")
            {
                MessageBox.Show("请输入测试名称", "提示");
                return false;
            }

            if (this.txt_testName.Text.Trim() != "")
            {
                List<Cls_Test> cltstlist = opertest.GetTestListByName(Mdl_Class.NowStectionId, this.txt_testName.Text.Trim());
                if (cltstlist != null && cltstlist.Count>0)
                {
                    MessageBox.Show("测试名称已存在,请重新输入", "提示");
                    return false;
                }
            }


            if (this.txt_AverageNo.Text.Trim() == "")
            {
                MessageBox.Show("请输入平均次数", "提示");
                return false;
            }

            if (this.txt_AverageNo.Text.Trim() != "")
            {
                try
                {


                    if (Convert.ToInt32(this.txt_AverageNo.Text.Trim()) <= 0)
                    {
                        MessageBox.Show("平均次数必须是大于0的整数", "提示");
                        return false;
                    }
                }
                catch (Exception)
                {

                    MessageBox.Show("平均次数必须是大于0的整数", "提示");
                    return false;
                }
            }
            return true;
        }

        private void txt_AverageNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {

                e.Handled = true;

            }
        }

        private void cmb_bandwidth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmb_specLines.Text!="")
            {
            this.txt_resolution.Text = Math.Round(Convert.ToDouble(this.cmb_bandwidth.Text) / Convert.ToDouble(this.cmb_specLines.Text),3).ToString();
            }
        }

        private void cmb_specLines_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.txt_resolution.Text = Math.Round(Convert.ToDouble(this.cmb_bandwidth.Text) / Convert.ToDouble(this.cmb_specLines.Text), 3).ToString();
        }






        public bool InitUnit()
        {
            //foreach (Cls_ACQUnit acq in _Project.ACQUnitList.ACQUnitList)
            //{
            //    //初始化所有ACQTCPIP
            //    acq.MyTcpIpControl = new TcpIpControl(acq);
            //    //初始化所有ACQTCPIP
            //    acq.MyTcpIpControl.Init();
            //    //尝试握手
            //    acq.MyTcpIpControl.TryConnect(RetryCount);
            //}
            Cls_Scoket cls_socketset = socketset.GetSocket();
            if (cls_socketset == null || cls_socketset.IpAddress == "" || cls_socketset.Port==0)
            {
                MessageBox.Show("请正确配置下位机IP地址和端口号","提示");
                return false;
            }
            tp = new TcpIpControl(cls_socketset.IpAddress, cls_socketset.Port);

            Mdl_Class.IsQuitProgram = false;
            Mdl_Class.SendInstruct = "startdata";
            List<Common.DBOper.Cls_Channel> channelllist = opertechannel.GetChannelList(Mdl_Class.NowStectionId);
            Mdl_Class.NowRunTestStectionId = Mdl_Class.NowStectionId;
            if (tp.Init())
            {
                Mdl_Class.TestModel = 2;
                this.bt_run.BackColor = Color.Lime;
                this.bt_stop.BackColor = Color.White;
                this.bt_run.Enabled = false;
                this.bt_stop.Enabled = true;
                MachineTime machinetime = new MachineTime();
                machinetime.Year = (short)DateTime.Now.Year;
                machinetime.Month = (byte)DateTime.Now.Month;
                machinetime.Day = (byte)DateTime.Now.Day;
                machinetime.Hour = (byte)DateTime.Now.Hour;
                machinetime.Minute = (byte)DateTime.Now.Minute;
                machinetime.Second = (byte)DateTime.Now.Second;

                tp.SendMachineTime(machinetime);

                SamplingConfig SamplingConfig = new SamplingConfig();
                SamplingConfig.Average = Convert.ToByte(Mdl_Class.AverageNO);
                SamplingConfig.SampleRate = Convert.ToUInt16(Mdl_Class.SampFreq_index);
                SamplingConfig.Lines = Convert.ToUInt32(Mdl_Class.LineNO);
                SamplingConfig.AverageMod = Convert.ToByte(Mdl_Class.AverageMod);
                SamplingConfig.WindowFunction = Convert.ToByte(Mdl_Class.WindowFunction);

                tp.SendSampling(SamplingConfig);

                Mdl_Class.ChannelDataList.Clear();
                Mdl_Class.ChannelDataCount.Clear();
                Mdl_Class.ChannelOldDataList.Clear();
                for (int i = 0; i < channelllist.Count;i++ )
                {
                   
                        ACQParametersConfig acqconfig = new ACQParametersConfig();

                    acqconfig.ChannelNo = channelllist[i].ChannelId;//通道ID
                    acqconfig.ChannelID = GetStringToBytes(64, channelllist[i].ChannelName);
                    acqconfig.Enable = channelllist[i].IsUse;
                    acqconfig.Name = GetStringToBytes(128, channelllist[i].TestPointName);
                    acqconfig.Direction = channelllist[i].Direction;
                    acqconfig.SigType = channelllist[i].SigType;
                    acqconfig.SigUnit = channelllist[i].SigUnit;
                    acqconfig.Sensitivity = channelllist[i].Sensitivity;
                    acqconfig.SensitivityUnit = channelllist[i].SensitivityUnit;
                    acqconfig.SensorType = GetStringToBytes(128, channelllist[i].SensorType);
                    acqconfig.SensorManufacture = GetStringToBytes(128, channelllist[i].SensorManufacturer);
                    acqconfig.SensorNo = channelllist[i].SensorNo.Trim() == "" ? 0 : Convert.ToUInt64(channelllist[i].SensorNo.Trim());
                    tp.SendACQParametersConfig(acqconfig);
                    if (channelllist[i].IsUse == (byte)1)
                    {
                        List<Cls_Data> channdata = new List<Cls_Data>();
                        List<float> channelfloat = new List<float>();
                        Mdl_Class.ChannelDataList.Add(channelllist[i].ChannelId, channdata);
                        Mdl_Class.ChannelDataCount.Add(channelllist[i].ChannelId,0);
                        Mdl_Class.ChannelOldDataList.Add(channelllist[i].ChannelId, channelfloat);
                    }
                }
                this.progressBar1.Maximum = Mdl_Class.ChannelDataList.Count* Convert.ToInt32(this.txt_AverageNo.Text) + 1;
                //acqconfig.ChannelNo = 3;//通道ID
                //acqconfig.ChannelID = GetStringToBytes(64, "input3");
                //acqconfig.Enable = 1;
                //acqconfig.Name = GetStringToBytes(128, "ponit3");
                //acqconfig.Direction = 1;
                //acqconfig.SigType = 1;
                //acqconfig.SigUnit = 0;
                //acqconfig.Sensitivity = 6.0f;
                //acqconfig.SensitivityUnit = 4;
                //acqconfig.SensorType = GetStringToBytes(128, "型号3");
                //acqconfig.SensorManufacture = GetStringToBytes(128, "制作商3");
                //acqconfig.SensorNo = 78910;

                //tp.SendACQParametersConfig(acqconfig);




                tp.MyTcpIpState = TcpIpState.Connection;
                tp.SendString(Mdl_Class.SendInstruct);
                //kp.Value.TryConnect(RetryCount);
                Mdl_Class.startTime = DateTime.Now;
                Mdl_Class.ConnectTime.Restart();
                Mdl_Class.LowerMachineIsConnect = true;
                Program.form1.SetCmb_Section(false);
                return true;
            }
            else 
            {
                
                return false;
            }
                
            
            //if (headbeatThread != null && headbeatThread.IsAlive)
            //{
            //    headbeatThread.Abort();
            //}
            //headbeatThread = new Thread(KeepConnect);
            //headbeatThread.IsBackground = true;
            //headbeatThread.Start();
            //for (int i = 0; i < _Project.ACQUnitList.ACQUnitList.Count; i++)
            //{
            //    //_Project.ACQUnitList.ACQUnitList[i].InitTcpipControl();
            //    //初始化所有ACQTCPIP
            //    _Project.ACQUnitList.ACQUnitList[i].MyTcpIpControl.Init();
            //    //尝试握手
            //    _Project.ACQUnitList.ACQUnitList[i].MyTcpIpControl.TryConnect(RetryCount);
            //}
        }

        public byte[] GetStringToBytes(int bytelegth,string str) 
        {
            byte[] bytelist = new byte[bytelegth];

            byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);
            for (int i = 0; i < byteArray.Length; i++)
            {
                if (i < bytelegth)
                {
                    bytelist[i] = byteArray[i];
                }
            }
            return bytelist;
        }


        public void KeepConnect()
        {
            do
            {
                if (Mdl_Class.IsQuitProgram)
                {
                    break;
                }

                //foreach (KeyValuePair<int, TcpIpControl> kp in DicTcpIpControl)
                //{
                if (tp.clientSocket == null || tp.clientSocket.Connected == false || tp.MyTcpIpState == TcpIpState.Disconnection)
                    {
                        if (tp.Init())
                        {

                            //MachineTime machinetime = new MachineTime();
                            //machinetime.Year = (short)DateTime.Now.Year;
                            //machinetime.Month = (byte)DateTime.Now.Month;
                            //machinetime.Day = (byte)DateTime.Now.Day;
                            //machinetime.Hour = (byte)DateTime.Now.Hour;
                            //machinetime.Minute = (byte)DateTime.Now.Minute;
                            //machinetime.Second = (byte)DateTime.Now.Second;
                            tp.MyTcpIpState = TcpIpState.Connection;
                            //tp.SendMachineTime(machinetime);
                            //tp.TryConnect(RetryCount);
                            if (Mdl_Class.SendInstruct != "")
                            {
                                tp.SendString(Mdl_Class.SendInstruct);
                            }
                            else
                            {
                                tp.SendString("startData");
                            }
                            Mdl_Class.startTime = DateTime.Now;
                        }
                        else
                        {
                            tp.MyTcpIpState = TcpIpState.Disconnection;
                        }
                    }
                    else
                    {
                        TimeSpan ts1 = new TimeSpan(Mdl_Class.startTime.Ticks);
                        TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                        TimeSpan ts3 = ts1.Subtract(ts2).Duration();
                        if (ts3.TotalSeconds > 10)
                        {

                            tp.MyTcpIpState = TcpIpState.Disconnection;

                        }


                    }
                //}
                Thread.Sleep(1000);
            } while (true);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.progressBar1.Value = Mdl_Class.TestProgress;
            //if (this.progressBar1.Value==Mdl_Class.AverageNO)
            //{
            
            //}

            if (Mdl_Class.ConnectTime.ElapsedMilliseconds > 60000)
            {
                this.lb_connectstate.Text = "下位机状态:已断开";
                this.lb_connectstate.ForeColor = Color.Red;
                Mdl_Class.LowerMachineIsConnect = false;
            }
            else 
            {
                this.lb_connectstate.Text = "下位机状态:已连接";
                this.lb_connectstate.ForeColor = Color.Green;
                Mdl_Class.LowerMachineIsConnect = true;
            }


            if( Mdl_Class.LowerMachineIsConnect ==false)
            {
                this.timer1.Stop();
                if (MessageBox.Show("与下位机通讯中断，是否重连？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.Yes)
                {
                    InitUnit();
                    this.timer1.Start();
                    timer2.Start();
                }
                else 
                {
                    if (MessageBox.Show("测试还未结束，现在结束通讯，数据将丢失，确定放弃重连吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.Yes)
                    {
                        Mdl_Class.SendInstruct = "stopdata";
      
                        Mdl_Class.IsQuitProgram = true;
                        Thread.Sleep(1000);
                        if (tp != null)
                        {

                            tp.Dispose();
                            tp = null;
                        }
                        this.bt_run.BackColor = Color.White;
                        this.bt_stop.BackColor = Color.Lime;
                        this.bt_run.Enabled = true;
                        this.bt_stop.Enabled = false;
                        Program.frmmain.ReflashTestName();
                        MessageBox.Show("测试结束", "提示");
                        this.lb_connectstate.Text = "下位机状态:已断开";
                        this.lb_connectstate.ForeColor = Color.Red;
                        progressBar1.Value = 0;
                        Program.form1.SetCmb_Section(true);
                        Mdl_Class.TestModel = 0;
                        timer2.Stop();
                    }
                    else 
                    {
                        InitUnit();
                        this.timer1.Start();
                    }
                }
            }
            if (this.progressBar1.Value == this.progressBar1.Maximum)
            {
                Mdl_Class.SendInstruct = "stopdata";
                this.timer1.Stop();
                //
                if (tp != null)
                {
                    tp.SendString("stopdata");
                }

                Mdl_Class.IsQuitProgram = true;
                Thread.Sleep(1000);
                if (tp != null)
                {
          
                    tp.Dispose();
                    tp = null;
                }
                this.bt_run.BackColor = Color.White;
                this.bt_stop.BackColor = Color.Lime;
                this.bt_run.Enabled = true;
                this.bt_stop.Enabled = false;
                Program.frmmain.ReflashTestName();
                MessageBox.Show("测试结束","提示");
                this.lb_connectstate.Text = "下位机状态:已断开";
                this.txt_testName.Text = this.txt_testName.Text + "_1";
                this.lb_connectstate.ForeColor = Color.Red;
                progressBar1.Value = 0;
                Program.form1.SetCmb_Section(true);
                Mdl_Class.TestModel = 0;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            float[] arry = new float[] { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f };

            float[] arry1 = new float[] { 0.1f, 0.21f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f };

            //arry[0] = (float)(arry[0] | 1);

            List<float> Result = arry.Concat(arry1).ToList<float>();

            string result = String.Join(",", Result);

            Console.WriteLine(result);
        }


        Dictionary<string, Common.DBOper.Cls_Channel> testPonitNameToChannel = new Dictionary<string, Common.DBOper.Cls_Channel>();
        private void cmb_channel_MouseClick(object sender, MouseEventArgs e)
        {
            

        }

        public void LoadChannel() 
        {
            List<Common.DBOper.Cls_Channel> channlist = opertechannel.GetChannelList(Mdl_Class.NowStectionId);
            this.cmb_channel.Items.Clear();
            testPonitNameToChannel.Clear();
            if (channlist != null && channlist.Count > 0)
            {
                for (int i = 0; i < channlist.Count; i++)
                {
                    if (channlist[i].IsUse == (byte)1)
                    {
                        this.cmb_channel.Items.Add(channlist[i].TestPointName);
                        testPonitNameToChannel.Add(channlist[i].TestPointName, channlist[i]);
                    }
                }
                this.cmb_channel.SelectedIndex = 0;
            }

        }

        private void cmb_channel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmb_channel.SelectedIndex >= 0 && cmb_dataType.SelectedIndex >= 0)
            {
                Mdl_Class.OnLineChannelId = testPonitNameToChannel[this.cmb_channel.Text].ChannelId;
           
            }
        
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Stop();
            try
            {

                string ChartTypeName = this.cmb_dataType.Text;
                List<float> displayvalue = new List<float>();
                if (Mdl_Class.onlinchannelData.Count > 0&& Mdl_Class.OnLineChannelId>0)
                {
                    object accdata = Mdl_Class.onlinchannelData.ToArray()[0];
                    int datachannelid = 0;
                    Mdl_Class.WriteLog.sysErrLog("刷新图表开始", ChartTypeName + "  通道" + Mdl_Class.OnLineChannelId.ToString());
                    switch (Mdl_Class.LineNO)
                    {

                        case 256:
                            Acceleration_256 accdate_256 = (Acceleration_256)accdata;
                            datachannelid = accdate_256.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_256.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_256.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_256._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_256.highdB.ToString();
                            this.lb_lowdB.Text = accdate_256.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_256.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_256.velocityRMS.ToString();
                            break;
                        case 512:
                            Acceleration_512 accdate_512 = (Acceleration_512)accdata;
                            datachannelid = accdate_512.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_512.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_512.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_512._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }

                            this.lb_highdB.Text = accdate_512.highdB.ToString();
                            this.lb_lowdB.Text = accdate_512.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_512.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_512.velocityRMS.ToString();
                            break;
                        case 1024:
                            Acceleration_1024 accdate_1024 = (Acceleration_1024)accdata;
                            datachannelid = accdate_1024.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_1024.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_1024.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_1024._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_1024.highdB.ToString();
                            this.lb_lowdB.Text = accdate_1024.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_1024.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_1024.velocityRMS.ToString();
                            break;
                        case 2048:
                            Acceleration_2048 accdate_2048 = (Acceleration_2048)accdata;
                            datachannelid = accdate_2048.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_2048.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_2048.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_2048._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_2048.highdB.ToString();
                            this.lb_lowdB.Text = accdate_2048.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_2048.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_2048.velocityRMS.ToString();
                            break;
                        case 4096:
                            Acceleration_4096 accdate_4096 = (Acceleration_4096)accdata;
                            datachannelid = accdate_4096.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_4096.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_4096.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_4096._1_3octavedB.ToList();
                                    break;
                               
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_4096.highdB.ToString();
                            this.lb_lowdB.Text = accdate_4096.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_4096.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_4096.velocityRMS.ToString();
                            break;
                        case 8192:
                            Acceleration_8192 accdate_8192 = (Acceleration_8192)accdata;
                            datachannelid = accdate_8192.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_8192.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_8192.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_8192._1_3octavedB.ToList();
                                    break;
                            
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_8192.highdB.ToString();
                            this.lb_lowdB.Text = accdate_8192.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_8192.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_8192.velocityRMS.ToString();
                            break;
                        case 16384:
                            Acceleration_16384 accdate_16384 = (Acceleration_16384)accdata;
                            datachannelid = accdate_16384.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_16384.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_16384.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_16384._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_16384.highdB.ToString();
                            this.lb_lowdB.Text = accdate_16384.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_16384.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_16384.velocityRMS.ToString();
                            break;
                        case 32768:
                            Acceleration_32768 accdate_32768 = (Acceleration_32768)accdata;
                            datachannelid = accdate_32768.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_32768.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_32768.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_32768._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_32768.highdB.ToString();
                            this.lb_lowdB.Text = accdate_32768.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_32768.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_32768.velocityRMS.ToString();
                            break;
                        case 65536:
                            Acceleration_65536 accdate_65536 = (Acceleration_65536)accdata;
                            datachannelid = accdate_65536.ChannelId;
                            switch (ChartTypeName)
                            {
                                case "频谱数据":
                                    displayvalue = accdate_65536.accelerationFFTAmpDB.ToList();
                                    break;
                                case "时域数据":
                                    displayvalue = accdate_65536.accelerationTimewave.ToList();
                                    break;
                                case "1/3倍频程":
                                    displayvalue = accdate_65536._1_3octavedB.ToList();
                                    break;
                                default:
                                    break;
                            }
                            this.lb_highdB.Text = accdate_65536.highdB.ToString();
                            this.lb_lowdB.Text = accdate_65536.lowdB.ToString();
                            this.lb_totaldB.Text = accdate_65536.totaldB.ToString();
                            this.lb_velocityRMS.Text = accdate_65536.velocityRMS.ToString();
                            break;
                        default:
                            break;
                    }
                    Mdl_Class.onlinchannelData.Clear();
       
                    if (datachannelid == Mdl_Class.OnLineChannelId)
                    {

                        if (displayvalue != null && displayvalue.Count > 0)
                        {

                            double[] x_value = new double[displayvalue.Count];
                            double[] y_value = new double[displayvalue.Count];
                            for (int i = 0; i < displayvalue.Count; i++)
                            {

                                if (ChartTypeName == "频谱数据")
                                {
                                    //x_value[i] = i + 1;
                                    x_value[i] = Math.Round((double)(i + 1) * Math.Round(Convert.ToDouble(Mdl_Class.SampFreq) / Convert.ToDouble(Mdl_Class.LineNO), 2), 2);
                                    y_value[i] = Math.Round(Convert.ToDouble(displayvalue[i]), 3);
                                }
                                else if (ChartTypeName == "时域数据")
                                {
                                    x_value[i] = (double)(i + 1) / (Convert.ToDouble(Mdl_Class.SampFreq) * 2.0);
                                    y_value[i] = Math.Round(Convert.ToDouble(displayvalue[i]), 4);
                                }
                                else 
                                {
                                    x_value[i] = i + 1;
                                    y_value[i] = Math.Round(Convert.ToDouble(displayvalue[i]), 3);
                                }
                         
        
                            }
                            this.chart1.Series.Clear();

                            Thread.Sleep(200);

                            //}

                            Series ser = new Series();
                            if (ChartTypeName == "1/3倍频程")
                            {
                                ser.ChartType = SeriesChartType.Column;
                                for (int i = 0; i < ser.Points.Count; i++)
                                {
                                    ser.Points[i].AxisLabel = axis_txt[i].ToString();
                                }
                            }
                            else
                            {
                                ser.ChartType = SeriesChartType.Line;
                            }
                            ser.Color = Color.Red;
                            ser.Points.DataBindXY(x_value, y_value);
                            ser.Name = testPonitNameToChannel[this.cmb_channel.Text].TestPointName;
                            ser.LegendText = testPonitNameToChannel[this.cmb_channel.Text].TestPointName;


                            if (ChartTypeName.Contains("原始数据") || ChartTypeName.Contains("时域"))
                            {
                                this.chart1.ChartAreas[0].AxisX.Title = "单位(s)";
                                this.chart1.ChartAreas[0].AxisY.Title = "";
                            }
                            else if (ChartTypeName.Contains("频谱数据"))
                            {
                                this.chart1.ChartAreas[0].AxisX.Title = "单位(HZ)";
                                this.chart1.ChartAreas[0].AxisY.Title = "单位(dB)";
                            }
                            else
                            {
                                this.chart1.ChartAreas[0].AxisX.Title = "";
                                this.chart1.ChartAreas[0].AxisY.Title = "柱状图";
                            }


                            if (ChartTypeName.Contains("频谱"))
                            {
                                this.chart1.ChartAreas[0].AxisY.Minimum = y_value.ToArray().Min() - 10;
                            }
                            else
                            {
                                this.chart1.ChartAreas[0].AxisY.Minimum = y_value.ToArray().Min();
                            }
                            if (ChartTypeName.Contains("频谱"))
                            {
                                this.chart1.ChartAreas[0].AxisY.Maximum = y_value.ToArray().Max() + 10;
                                this.chart1.ChartAreas[0].AxisX.IsLogarithmic = true;
                            }
                            else
                            {
                                this.chart1.ChartAreas[0].AxisY.Maximum = y_value.ToArray().Max() * 1.5;
                                this.chart1.ChartAreas[0].AxisX.IsLogarithmic = false;
                            }

                            this.chart1.Series.Add(ser);
                            this.chart1.DataBind();
                            Mdl_Class.WriteLog.sysErrLog("刷新图表完成", ChartTypeName + "  通道" + datachannelid.ToString());
                        }
                    }
                }

            }
            catch (Exception ex)
            {

                Mdl_Class.WriteLog.sysErrLog("刷新图表异常", ex.Message.ToString());
            }

            timer2.Start();
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {

                e.Handled = true;

            }
        }

        private void txt_AverageNo_TextChanged(object sender, EventArgs e)
        {
            if (txt_AverageNo.Text!="") 
            {
                this.txt_time.Text =Convert.ToInt32( Convert.ToDouble(txt_AverageNo.Text) /Convert.ToDouble(txt_resolution.Text)).ToString();
            }
        }
    }
}
